package config

import (
	"github.com/hwcer/yyds"
	"server/share/protoc"
	"sort"
)

const (
	ShopShelfRefreshName  = "ShopShelfRefresh"
	ShopShelfDiscountName = "ShopShelfDiscount"
	ShopPurchasePriceName = "SShopPurchasePrice"
)

func init() {
	yyds.Config.Register(&shop{})
}

type ShopPurchasePrice struct {
	dict  map[int32]*protoc.ShopPurchasePrice //次数
	limit *protoc.ShopPurchasePrice           //上限
}

type ShopShelfRefresh = map[int32][]int32
type ShopShelfDiscount = map[int32][]int32

func GetShopRefreshShelf(shopId int32) []int32 {
	d := yyds.Config.Process.Get(ShopShelfRefreshName).(ShopShelfRefresh)
	v := d[shopId]
	if v == nil {
		return nil
	}
	r := make([]int32, len(v))
	copy(r, v)
	return r
}
func GetShopShelfDiscount(shelfId int32) []int32 {
	d := yyds.Config.Process.Get(ShopShelfDiscountName).(ShopShelfDiscount)
	v := d[shelfId]
	if v == nil {
		return nil
	}
	r := make([]int32, len(v))
	copy(r, v)
	return r
}
func GetShopPurchasePrice(goods, num int32) *protoc.ShopPurchasePrice {
	d := yyds.Config.Process.Get(ShopPurchasePriceName).(map[int32]*ShopPurchasePrice)
	v := d[goods]
	if v == nil {
		return nil
	}
	if num >= v.limit.Num {
		return v.limit
	}
	r, _ := v.dict[num]
	return r
}

type shop struct {
	HandleDefault
}

func (this *shop) Handle(c *yyds.CS, i any) {
	data := i.(*output)
	//刷新规则
	r := ShopShelfRefresh{}
	for _, shelf := range data.ShopShelf {
		r[shelf.ShopId] = append(r[shelf.ShopId], shelf.Id)
	}
	c.Process.Set(ShopShelfRefreshName, r)
	//优惠信息
	d := ShopShelfDiscount{}
	for _, dis := range data.ShopShelfDiscount {
		for _, k := range dis.Shelf {
			d[k] = append(d[k], dis.Id)
		}
	}
	//按权重排序
	for _, v := range d {
		sort.Slice(v, func(i, j int) bool {
			ci := data.ShopShelfDiscount[v[i]]
			cj := data.ShopShelfDiscount[v[j]]
			return ci.Weight > cj.Weight
		})
	}
	c.Process.Set(ShopShelfDiscountName, d)
	//直购，快速购买
	p := make(map[int32]*ShopPurchasePrice)
	for _, v := range data.ShopPurchasePrice {
		id := v.Goods
		dict := p[id]
		if dict == nil {
			dict = &ShopPurchasePrice{dict: make(map[int32]*protoc.ShopPurchasePrice)}
			p[id] = dict
		}
		dict.dict[v.Num] = v
		if dict.limit == nil || v.Num > dict.limit.Num {
			dict.limit = v
		}
	}
	c.Process.Set(ShopPurchasePriceName, p)
	return
}
